<template>
  <div class="quill-editor">
    <!-- 富文本框 -->
    <div class="editor" ref="editor"></div>
    <!-- 图片上传器 -->
    <el-upload
      :action="serverUrl"
      name="file"
      ref="upload"
      :show-file-list="false"
      :on-success="uploadSuccess"
      :on-error="uploadError"
      :before-upload="beforeUpload">
    </el-upload>
  </div>
</template>
<script>
import Quill from "quill"
import "quill/dist/quill.core.css"
import "quill/dist/quill.snow.css"
import "quill/dist/quill.bubble.css"
import imageResize from 'quill-image-resize-module'
Quill.register('modules/imageResize',imageResize)
export default {
  name: 'quillEditor',
  props: {
    defaultData: {
      type: String,
      default: ''
    }
  },
  data() {
    return {
      Quill: null,
      currentValue: '',
      note: this.defaultData,
      // currentValue: '',
      // 这里写你要上传的图片服务器地址
      serverUrl: 'https://if.prowealthgroup.cn/task-produce/public/index.php/task-upload',
      options: {
        theme: "snow",
        bounds: document.body,
        debug: "warn",
        modules: {
          // 工具栏配置
          toolbar: {
            container:[
              ['bold', 'italic'],        // 加粗，斜体，下划线，删除线
              [{ 'list': 'ordered' }, { 'list': 'bullet' }],    // 有序列表，无序列表
              [{ 'indent': '-1' }, { 'indent': '+1' }],         // 缩进
              [{ 'size': ['small', false, 'large', 'huge'] }],  // 字体大小
              [{ 'font': [] }], // 字体
              [{ 'align': [] }],    // 居中
              ['image'],  // 上传图片、上传视频
            ],
          },
          imageResize: {//控制图片编辑的，实现功能就是这一段代码
            displayStyles: {
              backgroundColor: "black",
              border: "none",
              color: "white",
            },
            modules: ["Resize", "DisplaySize", "Toolbar"],
          },
        },
        placeholder: "请输入内容"
      }
    }
  },
  beforeDestroy() {
    this.Quill = null;
  },
  watch: {
    currentValue: {
      handler: function(val, oldval) {
        this.$emit('getEditorContent', val)
      }
    },
    defaultData: {
      handler: function(val, oldval) {
        this.currentValue = val
        this.init()
      }
    }
  },
  methods: {
    init() {
      const editor = this.$refs.editor;
      this.Quill = new Quill(editor, this.options)
      // 如果设置了上传地址则自定义图片上传事件
      let toolbar = this.Quill.getModule("toolbar");
      toolbar.addHandler("image", (value) => {
        if (value) {
          this.$refs.upload.$children[0].$refs.input.click()
        } else {
          this.quill.format("image", false);
        }
      })
      this.Quill.pasteHTML(this.currentValue)
      this.Quill.on("text-change", (delta, oldDelta, source) => {
        const html = this.$refs.editor.children[0].innerHTML
        const text = this.Quill.getText()
        const quill = this.Quill
        this.currentValue = html
      })
    },
    // 富文本图片上传前
    beforeUpload(file) {
      console.log(file,'filefilefilefile');
      let regArr = ['.gif','.jpg','.jpeg','.png']
      let lastName = file.name.slice(file.name.indexOf('.'))
      if (regArr.indexOf(lastName)==-1) {
        this.$message.error(`仅支持.gif/.jpg/.jpeg/.png格式!`);
        return false;
      }
      // 校检文件大小
      if (this.fileSize) {
        const isLt = file.size / 1024 / 1024 < this.fileSize;
        if (!isLt) {
          this.$message.error(`上传文件大小不能超过 ${this.fileSize} MB!`);
          return false;
        }
      }
      return true
    },
    uploadSuccess(res, file) {
      // 获取富文本组件实例
      let quill = this.Quill;
      // 如果上传成功
      if (res.status == 200 ) {
        // 获取光标所在位置
        let length = quill.getSelection().index;
        // 插入图片 res.url为服务器返回的图片地址
        quill.insertEmbed(length, 'image', res.data.imgUrl)
        // 调整光标到最后
        quill.setSelection(length + 1)
      } else {
        this.$message.error('图片插入失败')
      }
    },
    // 富文本图片上传失败
    uploadError() {
      this.$message.error('图片插入失败')
    }
  }
}
</script>
<style lang='less'>
.quill-editor { 
  width: 700px;
}
</style>
